#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智慧童话世界 - 增强版启动脚本
基于ERNIE-4.5-0.3B-Paddle模型的AI可选分支剧情童话书
集成MCP功能和智源研究院数据
"""

import sys
import os
import subprocess
import time
import webbrowser
from pathlib import Path

def check_dependencies():
    """检查依赖项"""
    print("🔍 检查项目依赖...")
    
    required_files = [
        "enhanced_fairy_tale_app.py",
        "advanced_ernie_integration.py", 
        "enhanced_mcp_integration.py",
        "enhanced_zhiyuan_integration.py",
        "templates/enhanced_index.html"
    ]
    
    missing_files = []
    for file in required_files:
        if not os.path.exists(file):
            missing_files.append(file)
    
    if missing_files:
        print(f"❌ 缺少必要文件: {missing_files}")
        return False
    
    print("✅ 所有必要文件检查完成")
    return True

def install_requirements():
    """安装Python依赖"""
    print("📦 安装Python依赖包...")
    
    requirements = [
        "flask",
        "paddlepaddle",
        "requests", 
        "numpy",
        "jieba",
        "beautifulsoup4"
    ]
    
    for package in requirements:
        try:
            print(f"安装 {package}...")
            subprocess.run([sys.executable, "-m", "pip", "install", package], 
                         check=True, capture_output=True)
        except subprocess.CalledProcessError as e:
            print(f"⚠️ 安装 {package} 失败: {e}")
    
    print("✅ 依赖安装完成")

def start_application():
    """启动应用"""
    print("🚀 启动智慧童话世界应用...")
    
    try:
        # 启动Flask应用
        process = subprocess.Popen([
            sys.executable, "enhanced_fairy_tale_app.py"
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        # 等待应用启动
        print("⏳ 等待应用启动...")
        time.sleep(3)
        
        # 检查应用是否成功启动
        if process.poll() is None:
            print("✅ 应用启动成功!")
            print("🌐 应用地址: http://localhost:5000")
            
            # 自动打开浏览器
            try:
                webbrowser.open("http://localhost:5000")
                print("🔗 已自动打开浏览器")
            except Exception as e:
                print(f"⚠️ 无法自动打开浏览器: {e}")
                print("请手动访问: http://localhost:5000")
            
            return process
        else:
            stdout, stderr = process.communicate()
            print(f"❌ 应用启动失败")
            print(f"错误信息: {stderr.decode('utf-8', errors='ignore')}")
            return None
            
    except Exception as e:
        print(f"❌ 启动过程出错: {e}")
        return None

def main():
    """主函数"""
    print("=" * 60)
    print("🌟 智慧童话世界 - AI可选分支剧情童话书")
    print("基于ERNIE-4.5-0.3B-Paddle模型")
    print("集成MCP功能和智源研究院数据")
    print("=" * 60)
    
    # 检查依赖
    if not check_dependencies():
        print("❌ 依赖检查失败，请确保所有必要文件存在")
        return
    
    # 安装依赖包
    install_requirements()
    
    # 启动应用
    process = start_application()
    
    if process:
        try:
            print("\n📝 应用运行中...")
            print("按 Ctrl+C 停止应用")
            process.wait()
        except KeyboardInterrupt:
            print("\n🛑 正在停止应用...")
            process.terminate()
            print("✅ 应用已停止")
    else:
        print("❌ 应用启动失败")

if __name__ == "__main__":
    main()